package com.incar.chuxing.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.incar.chuxing.R;
import com.incar.chuxing.api.ApiStore;
import com.incar.chuxing.api.UrlConstant;
import com.incar.chuxing.base.BaseActivity;
import com.incar.chuxing.bean.AccountInfoBean;
import com.incar.chuxing.bean.AlipayPreBean;
import com.incar.chuxing.bean.ChargeResultEvent;
import com.incar.chuxing.bean.DepositStatus;
import com.incar.chuxing.bean.QualificationBean;
import com.incar.chuxing.bean.ResultBean;
import com.incar.chuxing.bean.ReturnDepositBean;
import com.incar.chuxing.bean.WXPreBean;
import com.incar.chuxing.bean.WalletBean;
import com.incar.chuxing.payment.AlipayUtils;
import com.incar.chuxing.payment.WXPayUtils;
import com.incar.chuxing.utils.Constants;
import com.incar.chuxing.utils.Dialogs.PayResultDialog;
import com.incar.chuxing.utils.MyApplication;
import com.incar.chuxing.utils.Dialogs.ReturnDepositDialog;
import com.incar.chuxing.utils.SharedPreferencesKey;
import com.incar.chuxing.utils.Toast.ToastCompat;
import com.incar.chuxing.widget.NoScrollGridView;
import com.incar.chuxing.utils.SharedPreferencesUtils;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by jieyaozu on 2017/3/23.
 * 用户充值页面
 */

public class RechargeActivity extends BaseActivity {

    @BindView(R.id.title_name)
    TextView titleName;
    @BindView(R.id.title_tv_more)
    TextView titleTvMore;
    @BindView(R.id.title_more)
    ImageView ivMore;

    @BindView(R.id.charge_money_options)
    NoScrollGridView mGridView;
    @BindView(R.id.wallet_tv_geren)
    TextView myselfMoney;
    @BindView(R.id.charge_button)
    TextView btCharge;
    @BindView(R.id.weixin_radiobutton)
    RadioButton rbWeixin;
    @BindView(R.id.zfb_radiobutton)
    RadioButton rbZfb;
    @BindView(R.id.yue_radiobutton)
    RadioButton yeZf;
    @BindView(R.id.charge_money_wx)
    RelativeLayout chargeMoneyWx;
    @BindView(R.id.charge_money_zfb)
    RelativeLayout chargeMoneyZfb;
    @BindView(R.id.charge_money_line)
    View chargeMoneyLine;
    @BindView(R.id.scroll_content)
    ScrollView scrollContent;
    @BindView(R.id.wallet_tv_car_bzj)
    TextView walletTvCarBzj;
    @BindView(R.id.progressBar_my_account)
    RelativeLayout progressBar;
    private Context mContext = this;
    private GridViewAdapter gridViewAdapter;
    private int payMethod = 0;
    private double mBikeBail;
    private double mCarBail;


    @Override
    public int getLayoutId() {
        return R.layout.activity_charge_money;
    }

    @Override
    public void initData() {
        super.initData();
        EventBus.getDefault().register(this);
    }

    @Override
    public void initView() {
        titleName.setText("我的钱包");
        ivMore.setVisibility(View.GONE);
        titleTvMore.setVisibility(View.VISIBLE);
        titleTvMore.setText("充值明细");

        gridViewAdapter = new GridViewAdapter();
        mGridView.setAdapter(gridViewAdapter);
        scrollContent.setVisibility(View.GONE);
        progressBar.setVisibility(View.VISIBLE);
        //显示可用的支付方式
        if (SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_WXPAY_OPEN) == 1 && SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_ALIPAY_OPEN) == 1) {
            chargeMoneyWx.setVisibility(View.VISIBLE);
            chargeMoneyZfb.setVisibility(View.VISIBLE);
            chargeMoneyLine.setVisibility(View.VISIBLE);
            rbWeixin.setChecked(true);
            rbZfb.setChecked(false);

            payMethod = 1;
        } else if (SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_WXPAY_OPEN) == 1 && SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_ALIPAY_OPEN) == 0) {
            chargeMoneyWx.setVisibility(View.VISIBLE);
            chargeMoneyZfb.setVisibility(View.GONE);
            chargeMoneyLine.setVisibility(View.GONE);
            rbWeixin.setChecked(true);
            rbZfb.setChecked(false);

            payMethod = 1;
        } else if (SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_WXPAY_OPEN) == 0 && SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_ALIPAY_OPEN) == 1) {
            chargeMoneyWx.setVisibility(View.GONE);
            chargeMoneyZfb.setVisibility(View.VISIBLE);
            chargeMoneyLine.setVisibility(View.GONE);
            rbWeixin.setChecked(false);
            rbZfb.setChecked(true);
            payMethod = 2;
        } else {
            chargeMoneyWx.setVisibility(View.GONE);
            chargeMoneyZfb.setVisibility(View.GONE);
            chargeMoneyLine.setVisibility(View.GONE);
            payMethod = 0;
        }


        rbWeixin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    payMethod = 1;
                    rbZfb.setChecked(false);
                    scrollContent.fullScroll(ScrollView.FOCUS_DOWN);
                }
            }
        });


        rbZfb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    payMethod = 2;
                    rbWeixin.setChecked(false);
                    scrollContent.fullScroll(ScrollView.FOCUS_DOWN);
                }
            }
        });
        yeZf.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    payMethod = 3;
                    yeZf.setChecked(false);
                    scrollContent.fullScroll(ScrollView.FOCUS_DOWN);
                }
            }
        });
        getMoneyOptionsData();
        getMyWallet();
    }

    @OnClick({R.id.title_back, R.id.charge_button, R.id.wallet_car_deposit, R.id.title_tv_more})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.title_tv_more:
                Intent intent = new Intent(mContext, RechargeRecordActivity.class);
                startActivity(intent);
                break;
            case R.id.charge_button:
                if (payMethod == 1) {
                    getWxpayParams((int) (gridViewAdapter.getSelectPrice() * 100) + "");
                } else if (payMethod == 2) {
                    getAlipayParams((int) (gridViewAdapter.getSelectPrice() * 100) + "");
                }
                break;
            case R.id.wallet_car_deposit:
                if (mCarBail != 0) {
                    final ReturnDepositDialog selfDialog = new ReturnDepositDialog(mContext);
                    selfDialog.setMessage(getString(R.string.returnDepositHasBail));
                    selfDialog.setYesOnclickListener("确定", new ReturnDepositDialog.onYesOnclickListener() {
                        @Override
                        public void onYesClick() {
                            returnDeposit("1");
                            selfDialog.dismiss();
                        }
                    });
                    selfDialog.setNoOnclickListener("取消", new ReturnDepositDialog.onNoOnclickListener() {
                        @Override
                        public void onNoClick() {
                            selfDialog.dismiss();
                        }
                    });
                    selfDialog.show();
                } else {
                    checkCarUserStatusAndIntent();
                }
                break;

        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    @Subscribe
    public void onChargeResult(ChargeResultEvent event) {
        if (event.payResult == 0) { //充值成功
            progressBar.setVisibility(View.GONE);
            //1微信  2支付宝 3个人账户
            if (event.payMethod == 2 || event.payMethod == 1) {
                notifyPayDone();
            }
            final PayResultDialog payResultDialog = new PayResultDialog(mContext);
            payResultDialog.setResultTitle("充值成功");
            payResultDialog.setResultContent("充值成功，可返回钱包查看！");
            payResultDialog.setResultImage(R.drawable.icon_succeed);
            payResultDialog.show();
            new Handler(new Handler.Callback() {
                //处理接收到的消息的方法
                @Override
                public boolean handleMessage(Message arg0) {
                    //再次刷新请求信息
                    getMoneyOptionsData();
                    if (payResultDialog != null) {
                        payResultDialog.dismiss();
                    }
                    scrollContent.smoothScrollTo(0, 0);
                    return false;
                }
            }).sendEmptyMessageDelayed(0, 3000); //表示延时三秒进行任务的执行

        } else {  //充值失败
            progressBar.setVisibility(View.GONE);
            final PayResultDialog payResultDialog = new PayResultDialog(mContext);
            payResultDialog.setResultTitle("充值失败");
            payResultDialog.setResultContent("付款失败，请选择重新付款！");
            payResultDialog.setResultImage(R.drawable.icon_fail);
            payResultDialog.show();
            new Handler(new Handler.Callback() {
                //处理接收到的消息的方法
                @Override
                public boolean handleMessage(Message arg0) {
                    if (payResultDialog != null) {
                        payResultDialog.dismiss();
                    }
                    return false;
                }
            }).sendEmptyMessageDelayed(0, 2000); //表示延时三秒进行任务的执行
        }

    }

    private void notifyPayDone() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).notifyPayDone(((MyApplication) getApplication()).getRequestFieldMap(),
                SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.PAY_TRADE_NO),
                "0").enqueue(new Callback<ResultBean>() {
            @Override
            public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
            }

            @Override
            public void onFailure(Call<ResultBean> call, Throwable t) {
            }
        });

    }

    private void getMyWallet() {
        progressBar.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getWallet(((MyApplication) getApplication()).getRequestFieldMap()).enqueue(new Callback<WalletBean>() {
            @Override
            public void onResponse(Call<WalletBean> call, Response<WalletBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        progressBar.setVisibility(View.GONE);
                        DecimalFormat df = new DecimalFormat("0.00");
                        mBikeBail = response.body().getAttachment().getBikeBail();
                        mCarBail = response.body().getAttachment().getCarBail();
                      /*  walletTvJituan.setText(df.format(response.body().getAttachment().getEnterpriseBalance()) + "元");
                        walletTvGeren.setContent(df.format(response.body().getAttachment().getBalance()));
*/
                        if (df.format(mCarBail).equals("0.00")) {
                            walletTvCarBzj.setText(df.format(mCarBail) + "元");
                        } else {
                            walletTvCarBzj.setText(df.format(mCarBail) + "元");
                        }

                    } else {
                        progressBar.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    progressBar.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<WalletBean> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void checkCarUserStatusAndIntent() {
        progressBar.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getUserStatus(((MyApplication) getApplication()).getRequestFieldMap()).enqueue(new Callback<QualificationBean>() {
            @Override
            public void onResponse(Call<QualificationBean> call, Response<QualificationBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    progressBar.setVisibility(View.GONE);
                    if (response.body().getStatus() == 200) {

                        SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.REAL_NAME_STATUS, response.body().getAttachment().getIdentityStatus() + "");
                        SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.LICENSE_CAR_STATUS, response.body().getAttachment().getLicenseStatus() + "");

                        Intent intent = new Intent(RechargeActivity.this, QualificationActivity.class);
                        intent.putExtra("SubmitFlag", 3);
                        startActivity(intent);
                    } else {
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<QualificationBean> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, mContext.getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                Log.i("neterror", "008");
            }
        });
    }


    private void returnDeposit(String bailType) {
        progressBar.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).returnDeposit(((MyApplication) getApplication()).getRequestFieldMap(), bailType).enqueue(new Callback<ReturnDepositBean>() {
            @Override
            public void onResponse(Call<ReturnDepositBean> call, Response<ReturnDepositBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    progressBar.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    //退完后刷新一下
                    getMyWallet();
                } else {
                    progressBar.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ReturnDepositBean> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 获取金额数据
     */
    private void getMoneyOptionsData() {
        progressBar.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getAccountInfo(((MyApplication) getApplication()).getRequestFieldMap()).enqueue(new Callback<AccountInfoBean>() {
            @Override
            public void onResponse(Call<AccountInfoBean> call, Response<AccountInfoBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        scrollContent.setVisibility(View.VISIBLE);
                        progressBar.setVisibility(View.GONE);
                        AccountInfoBean.AttachmentBean.AccountModelBean account = response.body().getAttachment().getAccountModel();
                        DecimalFormat df = new DecimalFormat("0.00");
                        myselfMoney.setText(df.format(account.getBalance()));
                        List<AccountInfoBean.AttachmentBean.RechargeModelBean> chargeValue_list = response.body().getAttachment().getRechargeModel();
                        chargeValue_list.get(0).setChecked(true);
                        if (chargeValue_list != null && chargeValue_list.size() != 0) {
                            gridViewAdapter.replaceAll(chargeValue_list);
                        }
                    } else {
                        progressBar.setVisibility(View.GONE);
                        ToastCompat.makeText(RechargeActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    progressBar.setVisibility(View.GONE);
                    ToastCompat.makeText(RechargeActivity.this, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<AccountInfoBean> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                ToastCompat.makeText(RechargeActivity.this, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }


    /**
     * 微信充值
     *
     * @param chargeValue
     */
    private void getWxpayParams(String chargeValue) {
        progressBar.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).weChatRecharge(((MyApplication) getApplication()).getRequestFieldMap(), chargeValue, "2").enqueue(new Callback<WXPreBean>() {
            @Override
            public void onResponse(Call<WXPreBean> call, Response<WXPreBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        SharedPreferencesUtils.getInstance(RechargeActivity.this).putIntValue(SharedPreferencesKey.USER_PAY_TYPE, 2);
                        WXPreBean.AttachmentBean.BeanBean orderInfo = response.body().getAttachment().getBean();
                        WXPayUtils wxPayUtils = new WXPayUtils(RechargeActivity.this);
                        wxPayUtils.wxPay(orderInfo);
                    } else {
                        progressBar.setVisibility(View.GONE);
                        ToastCompat.makeText(RechargeActivity.this, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                } else {
                    progressBar.setVisibility(View.GONE);
                    ToastCompat.makeText(RechargeActivity.this, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<WXPreBean> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                ToastCompat.makeText(RechargeActivity.this, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 支付宝充值
     *
     * @param chargeValue
     */
    private void getAlipayParams(String chargeValue) {
        progressBar.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).aliPayRecharge(((MyApplication) getApplication()).getRequestFieldMap(), chargeValue, "1")
                .enqueue(new Callback<AlipayPreBean>() {
                    @Override
                    public void onResponse(Call<AlipayPreBean> call, Response<AlipayPreBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.USER_PAY_TYPE, 2);
                                SharedPreferencesUtils.getInstance(mContext).putStringValue(SharedPreferencesKey.PAY_TRADE_NO,
                                        response.body().getAttachment().getOutTradeNo());
                                String orderInfo = response.body().getAttachment().getStr();
                                AlipayUtils alipayUtils = new AlipayUtils(RechargeActivity.this);
                                alipayUtils.aliPay(orderInfo);
                            } else {
                                progressBar.setVisibility(View.GONE);
                                ToastCompat.makeText(RechargeActivity.this, response.body().getMessage(), Toast.LENGTH_LONG).show();
                            }
                        } else {
                            progressBar.setVisibility(View.GONE);
                            ToastCompat.makeText(RechargeActivity.this, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<AlipayPreBean> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        ToastCompat.makeText(RechargeActivity.this, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                    }
                });
    }


    public class GridViewAdapter extends BaseAdapter {
        private int selectPos = 0;
        private List<AccountInfoBean.AttachmentBean.RechargeModelBean> chargeValue_list = new ArrayList<>();

        public void replaceAll(List<AccountInfoBean.AttachmentBean.RechargeModelBean> rechargeModelBeanList) {
            if (rechargeModelBeanList != null) {
                chargeValue_list.clear();
                chargeValue_list.addAll(rechargeModelBeanList);
            }

            for (int i = 0; i < chargeValue_list.size(); i++) {
                AccountInfoBean.AttachmentBean.RechargeModelBean modelBean = chargeValue_list.get(i);
                if (modelBean.getRechargePrice() == 50) {
                    selectPos = i;
                }

            }
            notifyDataSetChanged();
        }

        public double getSelectPrice() {
            return chargeValue_list.get(selectPos).getRechargePrice();
        }

        @Override
        public int getCount() {
            return chargeValue_list.size();
        }

        @Override
        public Object getItem(int position) {
            return chargeValue_list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = View.inflate(RechargeActivity.this, R.layout.item_gridview_chargemoney, null);
            RelativeLayout background = (RelativeLayout) view.findViewById(R.id.layout_bg);
            AccountInfoBean.AttachmentBean.RechargeModelBean modelBean = chargeValue_list.get(position);

            if (selectPos == position) {
                background.setBackgroundResource(R.drawable.shape_green_corner);
            } else {
                background.setBackgroundResource(R.drawable.corner_gray_shape);
            }

            TextView tvChargeMoney = (TextView) view.findViewById(R.id.charge_money);
            TextView tvGiveMoney = (TextView) view.findViewById(R.id.give_money);
            TextView tvXianshi = (TextView) view.findViewById(R.id.xianshi_icon);

            tvChargeMoney.setText("充￥" + modelBean.getRechargePrice());
            if (modelBean.getExtraPrice() != 0) {
                tvGiveMoney.setVisibility(View.VISIBLE);
                tvXianshi.setVisibility(View.VISIBLE);
                tvGiveMoney.setText("送￥" + modelBean.getExtraPrice());
            } else {
                tvGiveMoney.setVisibility(View.GONE);
                tvXianshi.setVisibility(View.GONE);
            }

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    selectPos = position;
                    notifyDataSetChanged();
                    scrollContent.fullScroll(ScrollView.FOCUS_DOWN);
                }
            });
            return view;
        }
    }
}
